from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql
import os

app = Flask(__name__)
CORS(app)

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'port': 3306,
    'user': 'root',
    'password': '123456',
    'database': 'project_ji',
    'charset': 'utf8mb4',
    'autocommit': True
}

def get_db_connection():
    """获取数据库连接"""
    try:
        connection = pymysql.connect(**DB_CONFIG)
        return connection
    except Exception as e:
        print(f"数据库连接失败: {e}")
        return None
@app.route('/api/register', methods=['POST'])
def register():
    """用户注册接口"""
    try:
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        
        if not username or not email or not password:
            return jsonify({'error': '请填写所有字段'}), 400
        
        connection = get_db_connection()
        if not connection:
            return jsonify({'error': '数据库连接失败'}), 500
        
        cursor = connection.cursor()
        
        # 检查用户名或邮箱是否已存在
        check_sql = "SELECT id FROM users WHERE username = %s OR email = %s"
        cursor.execute(check_sql, (username, email))
        existing_user = cursor.fetchone()
        
        if existing_user:
            cursor.close()
            connection.close()
            return jsonify({'error': '用户名或邮箱已存在'}), 400
        
        # 插入新用户
        insert_sql = "INSERT INTO users (username, email, password) VALUES (%s, %s, %s)"
        cursor.execute(insert_sql, (username, email, password))
        connection.commit()
        
        user_id = cursor.lastrowid
        
        cursor.close()
        connection.close()
        
        return jsonify({
            'message': '注册成功',
            'user': {'id': user_id, 'username': username, 'email': email}
        }), 200
        
    except Exception as e:
        print(f"注册错误: {e}")
        return jsonify({'error': '注册失败'}), 500

@app.route('/api/login', methods=['POST'])
def login():
    """用户登录接口"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({'error': '请填写用户名和密码'}), 400
        
        connection = get_db_connection()
        if not connection:
            return jsonify({'error': '数据库连接失败'}), 500
        
        cursor = connection.cursor()
        
        # 查询用户
        sql = "SELECT * FROM users WHERE username = %s AND password = %s"
        cursor.execute(sql, (username, password))
        user = cursor.fetchone()
        
        cursor.close()
        connection.close()
        
        if not user:
            return jsonify({'error': '用户名或密码错误'}), 400
        
        return jsonify({
            'message': '登录成功',
            'user': user,
            'token': 'mock-token'
        }), 200
        
    except Exception as e:
        print(f"登录错误: {e}")
        return jsonify({'error': '登录失败'}), 500

@app.route('/api/user', methods=['GET'])
def get_user():
    """获取用户信息接口"""
    try:
        user_id = request.args.get('userId')
        
        if not user_id:
            return jsonify({'error': '缺少用户ID'}), 400
        
        connection = get_db_connection()
        if not connection:
            return jsonify({'error': '数据库连接失败'}), 500
        
        cursor = connection.cursor()
        
        sql = "SELECT id, username, email, created_at FROM users WHERE id = %s"
        cursor.execute(sql, (user_id,))
        user = cursor.fetchone()
        
        cursor.close()
        connection.close()
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        return jsonify({'user': user}), 200
        
    except Exception as e:
        print(f"获取用户信息错误: {e}")
        return jsonify({'error': '获取用户信息失败'}), 500

if __name__ == '__main__':
    app.run(debug=True, port=3001)
